<template>
  <el-dialog v-model="dialogVisible" title="图书资源" width="1000" align-center>
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="90px">
      <el-form-item label="关键词" prop="keyword">
        <el-input v-model="queryParams.keyword" class="!w-240px" clearable placeholder="请输入关键词"
                  @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <div style="height: 400px">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table-v2 :columns="columns" :data="tableModule.tableData" :width="width" :height="height" />
        </template>
      </el-auto-resizer>
    </div>
    <el-pagination :current-page="tableModule.currentPage" :page-size="tableModule.pageSize"
                   :page-sizes="[10, 20, 30, 50]" :small="false" :disabled="false" :background="false"
                   layout="total, sizes, prev, pager, next, jumper" :total="tableModule.count" @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="tsx" setup>
import { ref, unref } from 'vue'
import { ElCheckbox, CheckboxValueType, Column } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import * as FormApi from '@/api/knowledge/area'
import type { FunctionalComponent } from 'vue'
import bookLogo from '@/assets/imgs/bookLogo.webp'
const emit = defineEmits(['booksArray'])
const dialogVisible = ref(false) // 弹窗的是否展示
/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
}
const queryParams = reactive({
  keyword: null
})
const booksArray = reactive([])
const submitForm = () => {
  booksArray.splice(0, booksArray.length)
  tableModule.tableData.forEach((item, index) => {
    if (item.checked) booksArray.push(item)
  })
  emit('booksArray', booksArray)
  if (!booksArray) {
    ElMessage({
      message: '请选择图书资源',
      showClose: true,
      grouping: true,
      type: 'warning'
    })
    return
  }
  dialogVisible.value = false
}
// 表格数据
const tableModule = reactive({
  tableData: [], // 表格数据
  currentPage: 1, // 表格分页：当前页
  pageSize: 10, // 表格分页：每页显示条目个数
  count: 1 // 表格分页：总记录数
})
// 分页：pageSize 改变时会触发
const handleSizeChange = (val: number) => {
  tableModule.pageSize = val
  getTableData()
}
// 分页：currentPage 改变时会触发
const handleCurrentChange = (val: number) => {
  tableModule.currentPage = val
  getTableData()
}
// 列表查询
const getTableData = async () => {
  const params = {
    pageNo: tableModule.currentPage,
    pageSize: tableModule.pageSize,
    keyword: queryParams.keyword,
    status: 10,
  }
  FormApi.booksData(42, params).then((res) => {
    res.list.forEach((item) => (item.fn_cover = JSON.parse(item.fn_cover)))
    tableModule.tableData = res.list
    tableModule.count = res.total
    // ElMessage({
    //   message: '查询成功',
    //   grouping: true,
    //   showClose: true,
    //   type: 'success'
    // })
  })
}
getTableData()
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const handleQuery = () => {
  getTableData()
}
const queryFormRef = ref<any>()
const resetQuery = () => {
  queryFormRef.value.resetFields()
  console.log(queryParams)
  handleQuery()
}
type SelectionCellProps = {
  value: boolean
  intermediate?: boolean
  onChange: (value: CheckboxValueType) => void
}
const SelectionCell: FunctionalComponent<SelectionCellProps> = ({
                                                                  value,
                                                                  intermediate = false,
                                                                  onChange
                                                                }) => {
  return <ElCheckbox onChange={onChange} modelValue={value} indeterminate={intermediate} />
}
// console.log(SelectionCell)
const columns: Column<object>[] = [
  {
    key: 'selection',
    width: 50,
    cellRenderer: ({ rowData }) => {
      const onChange = (value: CheckboxValueType) => (rowData.checked = value)
      return <SelectionCell value={rowData.checked} onChange={onChange} />
    },
    headerCellRenderer: () => {
      const _data = unref(tableModule.tableData)
      const onChange = (value: CheckboxValueType) =>
        (tableModule.tableData.checked = _data.map((row) => {
          row.checked = value
          return row
        }))
      const allSelected = _data.every((row) => row.checked)
      const containsChecked = _data.some((row) => row.checked)
      return (
        <SelectionCell
          value={allSelected}
          intermediate={containsChecked && !allSelected}
          onChange={onChange}
        />
      )
    },
    first: true,
    second: true,
    third: true
  },
  {
    key: 'id',
    title: '编号',
    dataKey: 'id',
    width: 50,
    align: 'center',
    cellRenderer: ({ cellData: id }) => <div>{id}</div>
  },
  {
    key: 'fn_cover',
    title: '封面',
    dataKey: 'fn_cover',
    width: 100,
    align: 'center',
    cellRenderer: (data) => (
      <>
        <img
          v-show={data.rowData.fn_cover.length}
          src={data.rowData.fn_cover[0]?.url}
          height={50}
        />
        <img v-show={!data.rowData.fn_cover.length} src={bookLogo} height={50} />
        {/* <el-icon v-show={!data.rowData.fn_cover.length} size="25"><Picture /></el-icon> */}
      </>
    )
  },
  {
    key: 'fn_title',
    title: '书名',
    dataKey: 'fn_title',
    width: 230,
    align: 'center',
    cellRenderer: ({ cellData: fn_title }) => <div>{fn_title}</div>
  },
  {
    key: 'fn_isbn',
    title: 'ISBN',
    dataKey: 'fn_isbn',
    width: 230,
    align: 'center',
    cellRenderer: ({ cellData: fn_isbn }) => <div>{fn_isbn}</div>
  },
  {
    key: 'fn_publishername',
    title: '出版社',
    dataKey: 'fn_publishername',
    width: 230,
    align: 'center',
    cellRenderer: ({ cellData: fn_publishername }) => <div>{fn_publishername}</div>
  },
  {
    key: 'create_time',
    title: '创建时间',
    dataKey: 'create_time',
    width: 100,
    align: 'center'
  }
]
</script>
